package com.tienon.message.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.aop.framework.AopContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tienon.message.entity.Batch_main;
import com.tienon.message.entity.Push_App;
import com.tienon.message.entity.Raw_msg_batch;
import com.tienon.message.mapper.Batch_mainMapper;
import com.tienon.message.mapper.Raw_msg_batchMapper;
import com.tienon.message.util.StaticParamsUtil;
/*
 * 批量控制的serice
 * */
@Component
public class Batch_mainService {
	@Resource
	Batch_mainMapper batch_mainMapper;
	@Resource
	Raw_msg_batchMapper raw_msg_batchMapper;
	Logger log = Logger.getLogger(Batch_mainThread.class);
	@Resource
	LoadRawMsgService loadRawMsgService;
	
	@Resource
	LoadSendMsgService loadSendMsgService;

	/**
	 * 处理群发控制表
	 * @throws InterruptedException 
	 */
	@Transactional
	public Batch_main dealBathch_main() throws InterruptedException{
		//根据批次步骤获取控制表中的信息
		Batch_main batch_main = batch_mainMapper.selectByStep();
		
		log.info("2进入线程："+ Thread.currentThread().getName()+"批次号：");//+batch_main.getBatId()
		if(null==batch_main){
			log.info("空进入线程："+ Thread.currentThread().getName());
			Thread.currentThread().sleep(100);
			return batch_main;
		}
		if(batch_main.getStep() == StaticParamsUtil.STEPSPTG){
			batch_main.setStep(StaticParamsUtil.STEPZZCLZ);//设置步骤为装载处理中
		}
		if(batch_main.getStep() == StaticParamsUtil.STEPZZWC){
			batch_main.setStep(StaticParamsUtil.STEPCRFSBCLZ);//设置步骤为插入发送表处理中
		}
		batch_mainMapper.updateByPrimaryKey(batch_main);
		return batch_main;
	}
	
	/**
	 * 处理群发控制表文件
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public void dealFile(Batch_main batch_main) throws InterruptedException, ExecutionException{
		String path = batch_main.getFileName();
		try {
			long start = System.currentTimeMillis();
			InputStream is = new FileInputStream(path);//读取文件
			XSSFWorkbook wbook = new XSSFWorkbook(is);
			XSSFSheet sheet = wbook.getSheetAt(0);//获取第一张表
			List<Future<Boolean>> listFuture = new ArrayList<Future<Boolean>>();
			int i = 1;
			while(true){
				XSSFRow row = sheet.getRow(i - 1);//获取第i行数据
				if(null == row){
					break;
				}
				Raw_msg_batch raw_msg_batch = getRaw_msg_batch(batch_main);
				raw_msg_batch.setBatOrder(i+1);
				listFuture.add(loadRawMsgService.loadRawMsgTask(raw_msg_batch));
				if(i % 1000 == 0){
					int success = 0;
					int fail = 0;
					for(Future<Boolean> k : listFuture){
						if(k.get()){
							log.info("装载成功"+",批次号:"+batch_main.getBatId()+",批次序号:"+raw_msg_batch.getBatOrder());
							success++;
						}else{
							log.info("装载失败"+",批次号:"+batch_main.getBatId()+",批次序号:"+raw_msg_batch.getBatOrder());
							fail++;
						}
					}
					listFuture.clear();//清空list
					if(batch_main.getLoadSuccess() == null){
						batch_main.setLoadSuccess(0);
					}
					if(batch_main.getLoadFail() == null){
						batch_main.setLoadFail(0);
					}
					batch_main.setLoadSuccess(batch_main.getLoadSuccess() + success);
					batch_main.setLoadFail(batch_main.getLoadFail() + fail);
					updateBatch_main(batch_main);
				}
			    i++;
			}
			int success = 0;
			int fail = 0;
			for(Future<Boolean> k : listFuture){
				if(k.get()){
					success++;
				}else{
					fail++;
				}
			}
			listFuture.clear();//清空list
			if(batch_main.getLoadSuccess() == null){
				batch_main.setLoadSuccess(0);
			}
			if(batch_main.getLoadFail() == null){
				batch_main.setLoadFail(0);
			}
			batch_main.setLoadSuccess(batch_main.getLoadSuccess() + success);
			batch_main.setLoadFail(batch_main.getLoadFail() + fail);
			batch_main.setStep(StaticParamsUtil.STEPZZWC);
			updateBatch_main(batch_main);
			long end = System.currentTimeMillis();
			log.info("批次号："+batch_main.getBatId()+",装载完成所需时间："+(end - start));
			wbook.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private Raw_msg_batch getRaw_msg_batch(Batch_main batch_main){
		Raw_msg_batch raw_msg_batch = new Raw_msg_batch();
		raw_msg_batch.setMsg("好合好散哒哒哒哈哈哈哈哈哈哈哈哈");
		raw_msg_batch.setBsnCd("233433d");
		raw_msg_batch.setMsgType(0);
		raw_msg_batch.setPrior(1);
		raw_msg_batch.setReportFlag(0);
		raw_msg_batch.setSendWay(2);
		raw_msg_batch.setFilter(0);
		raw_msg_batch.setBatId(batch_main.getBatId());
		raw_msg_batch.setBatSlice(12121);
		raw_msg_batch.setSplitFlag(0);
		raw_msg_batch.setLinkFlag(0);
		raw_msg_batch.setSendNow(1);
		return raw_msg_batch;
	}
	private Push_App getPush_App(Raw_msg_batch raw_msg_batch){
		Push_App push_app = new Push_App();
		push_app.setBatId(raw_msg_batch.getBatId());
		push_app.setSerial(raw_msg_batch.getSerail());
		push_app.setSplitId(213131);
		push_app.setSplitTotal(1);
		push_app.setOccDate(new Date());
		push_app.setOccTime(new Date());
		push_app.setState(2);
		push_app.setMsg(raw_msg_batch.getMsg());
		push_app.setBsnCd(raw_msg_batch.getBsnCd());
		push_app.setMsgType(raw_msg_batch.getMsgType());
		push_app.setPrior(raw_msg_batch.getPrior());
		push_app.setSendTimes(raw_msg_batch.getSendTimes());
		push_app.setSendTime(new Date());
		push_app.setReportFlag(raw_msg_batch.getReportFlag());
		push_app.setSendWay(raw_msg_batch.getSendWay());
		push_app.setOutChannle("01");
		push_app.setOutChanCustomId("jsjssjsjsjsjsjsjsjsj");
		push_app.setFilter(raw_msg_batch.getFilter());
		push_app.setSplitFlag(raw_msg_batch.getSplitFlag());
		push_app.setLinkFlag(raw_msg_batch.getLinkFlag());
		push_app.setSendNow(raw_msg_batch.getSendNow());
		push_app.setFeeType(0);
		push_app.setFee(0);
		return push_app;
	}
	/**
	 * 处理发送原始表记录
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public void dealRaw_msg_batch(Batch_main batch_main) throws InterruptedException, ExecutionException{
		Integer bat_Id = batch_main.getBatId();
		long start = System.currentTimeMillis();
		while(true){
			List<Raw_msg_batch> list = raw_msg_batchMapper.selectByBatId(bat_Id);
			List<Future<Boolean>> listFuture = new ArrayList<Future<Boolean>>();
			if(list.size() == 0){
			    batch_main.setStep(StaticParamsUtil.STEPCRFSBWC);
			    updateBatch_main(batch_main);
			    break;
			}else{
				for(int i = 0;i < list.size(); i++){
					log.info("读取大小:"+list.size()+",i值为多少:"+i+",批次号:"+list.get(i).getBatId()+",序列号:"+list.get(i).getSerail()+",线程号"+Thread.currentThread().getName());
					Push_App push_app = getPush_App(list.get(i));
					listFuture.add(loadSendMsgService.loadAppSendMsgTask(push_app));
				}
				int success = 0;
				int fail = 0;
				for(Future<Boolean> k : listFuture){
					if(k.get()){
						log.info("插入发送表成功"+",批次号:"+batch_main.getBatId()+",序列号:"+list.get(success).getSerail()+",线程号:"+Thread.currentThread().getName());
						success++;
					}else{
						log.info("插入发送表失败"+",批次号:"+batch_main.getBatId()+",序列号:"+list.get(success).getSerail()+",线程号:"+Thread.currentThread().getName());
						fail++;
					}
				}
				if(batch_main.getSendSuccess() == null){
					batch_main.setSendSuccess(0);
				}
				if(batch_main.getSendFail() == null){
					batch_main.setSendFail(0);
				}
				batch_main.setSendSuccess(batch_main.getSendSuccess() + success);
				batch_main.setSendFail(batch_main.getSendFail() + fail);
				updateBatch_main(batch_main);
			}
		}
		long end = System.currentTimeMillis();
		log.info("批次号:"+batch_main.getBatId()+",插入发送表完成时间:" + (end - start));
	}
	
	@Transactional
	public void updateBatch_main(Batch_main batch_main){
		batch_mainMapper.updateByPrimaryKey(batch_main);
	}
}
